package io.aicn.lowcode.service.dbmanager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.aicn.lowcode.entity.dbmanager.DataDictionary;
import io.aicn.lowcode.mapper.dbmanager.DataDictionaryMapper;
import io.aicn.lowcode.service.dbmanager.IDataDictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典Service实现类
 * 
 * @author lowcode-generator
 * @since 2025-01-25
 */
@Slf4j
@Service
public class DataDictionaryServiceImpl extends ServiceImpl<DataDictionaryMapper, DataDictionary> 
        implements IDataDictionaryService {

    @Override
    public List<DataDictionary> listByType(String dictType) {
        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", dictType)
                   .eq("status", "0") // 只查询启用状态的字典项(0正常 1停用)
                   .orderByAsc("sort_order");
        
        return this.list(queryWrapper);
    }

    @Override
    public DataDictionary getByTypeAndCode(String dictType, String dictCode) {
        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", dictType)
                   .eq("dict_code", dictCode);
        
        return this.getOne(queryWrapper);
    }

    @Override
    public List<String> getDictTypes() {
        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT dict_type")
                   .orderByAsc("dict_type");
        
        List<DataDictionary> list = this.list(queryWrapper);
        return list.stream()
                  .map(DataDictionary::getDictType)
                  .distinct()
                  .collect(Collectors.toList());
    }

    @Override
    public String getDictLabel(String dictType, String dictCode) {
        DataDictionary dictionary = getByTypeAndCode(dictType, dictCode);
        return dictionary != null ? dictionary.getDictLabel() : null;
    }

    @Override
    public String getDictCode(String dictType, String dictLabel) {
        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", dictType)
                   .eq("dict_label", dictLabel)
                   .eq("status", "0"); // 只查询启用状态的字典项(0正常 1停用)
        
        DataDictionary dictionary = this.getOne(queryWrapper);
        return dictionary != null ? dictionary.getDictCode() : null;
    }
}